package com.jishe.filter;
import com.alibaba.fastjson.JSON;
import com.jishe.pojo.Result;
import com.jishe.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;


@Slf4j
//@WebFilter(urlPatterns = "/*")

public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取请求的url
        String url = req.getRequestURI().toString();
        log.info("请求的url是{}",url);
        //判断是否包含login
        if (url.contains("login")){
            log.info("登陆操作，放行");
            chain.doFilter(request,response);
            return;
        }
        //获取请求头中的令牌token
        String jwt = req.getHeader("token");
        if (!StringUtils.hasLength(jwt)){
            log.info("未登录，返回未登录信息");
            Result error= Result.error("NOT_LOGIN");//NOT_LOGIN会返回到登陆页面
            String notLoginJson = JSON.toJSONString(error);
            resp.getWriter().write(notLoginJson);
            return;

        }
        //解析token，如果解析失败返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("token解析失败，返回未登录信息");
            Result error=Result.error("NOT_LOGIN");
            String notLoginJson = JSON.toJSONString(error);
            resp.getWriter().write(notLoginJson);
            return;
        }
        //放行
        log.info("token解析成功，放行");
        chain.doFilter(request,response);
    }
}
